<?php

namespace App\Http\Controllers\OperationManagement;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\OperationManagement\GovernmentDevice;
use App\Models\OperationManagement\GovenmentDeviceFile;
use App\Models\SystemManagement\Department;
use App\Models\SystemManagement\Employee;
use Illuminate\Database\QueryException;
use App\Http\Requests\OperationManagement\GovernmentDeviceRequest;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Grimzy\LaravelMysqlSpatial\Types\Polygon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

/**
 * @group 基础信息管理->环卫->市政设施
 *
 * 采用 restful api
 *
 * Body Parameters 表示请求的所需要的参数
 *
 * Query Parameters 表示返回参数的名称
 */

class GovernmentDeviceController extends Controller
{
    /**
     * 市政部件查看列表
     *
     * @bodyParam device_name string required 设备名称
     * @bodyParam device_type_id int required 设备类型id 外键 设备类型表
     *
     * @queryParam name string 设备名称
     * @queryParam mark string 编号
     * @queryParam address string 地址
     * @queryParam type_id int required 设备类型id 外键 设备类型表
     * @queryParam governmentCategory->name string 设备类型名称
     * @queryParam location point 经纬度-点 115.24556 25.14551
     * @queryParam areas polygon 护栏-面 (0 0,4 0,4 4,0 4,0 0)
     * @queryParam specs string 规格
     * @queryParam number integer 数量
     * @queryParam unit char 单位
     * @queryParam factory string 厂家
     * @queryParam contacts string 联系人
     * @queryParam mobile string 手机号码
     * @queryParam property_company string 产权单位
     * @queryParam principal_id int 负责人id 外键 员工表
     * @queryParam employees->name string 负责人
     * @queryParam phone string 电话
     * @queryParam rfid intger RFID绑定
     * @queryParam files->file->local_url string 附件url地址
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $governmentDevice = new GovernmentDevice;
        $data = $governmentDevice->getList($request);
        return response()->json(encodeMsg($data,200));
    }

    /**
     * 添加市政部件
     *
     * @bodyParam name string 设备名称
     * @bodyParam mark string 编号
     * @bodyParam address string 地址
     * @bodyParam type_id int required 设备类型id 外键 设备类型表
     * @bodyParam location point 经纬度-点 115.24556 25.14551
     * @bodyParam areas polygon 护栏-面 (0 0,4 0,4 4,0 4,0 0)
     * @bodyParam specs string 规格
     * @bodyParam number integer 数量
     * @bodyParam unit char 单位
     * @bodyParam factory string 厂家
     * @bodyParam contacts string 联系人
     * @bodyParam mobile string 手机号码
     * @bodyParam property_company string 产权单位
     * @bodyParam principal_id int 负责人id 外键 员工表
     * @bodyParam phone string 电话
     * @bodyParam government_ids string 市政部件附件ids:1,2,3
     * @bodyParam rfid intger RFID绑定
     *
     * @queryParam name string 设备名称
     * @queryParam mark string 编号
     * @queryParam address string 地址
     * @queryParam type_id int required 设备类型id 外键 设备类型表
     * @queryParam location point 经纬度-点 115.24556 25.14551
     * @queryParam areas polygon 护栏-面 (0 0,4 0,4 4,0 4,0 0)
     * @queryParam specs string 规格
     * @queryParam number integer 数量
     * @queryParam unit char 单位
     * @queryParam factory string 厂家
     * @queryParam contacts string 联系人
     * @queryParam mobile string 手机号码
     * @queryParam property_company string 产权单位
     * @queryParam principal_id int 负责人id 外键 员工表
     * @queryParam phone string 电话
     * @queryParam rfid intger RFID绑定
     * @queryParam government_ids string 市政部件附件ids:1,2,3
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $data = $request->all();
            // $data['location'] = \DB::raw("GeomFromText('Point({$request->input('location')})')");
            $location = $request->input('location','');
            if(!empty($location)){
                $data['location'] = Point::fromString($location);
            }
            $areas = $request->input('areas','');
            if(!empty($areas)){
                $data['areas'] = Polygon::fromString($areas);
            }
            $governmentDevice = GovernmentDevice::create($data);
            if($request->has('government_ids')){
                $file_data = [];
                $fileArr = explode(',',$request->get('government_ids'));
                foreach ($fileArr as $k=>$value){
                    $tmp = [];
                    $tmp['file_id'] = $value;
                    $tmp['government_id'] = $governmentDevice->id;
                    array_push($file_data,$tmp);
                }
                try{
                    GovenmentDeviceFile::insert($file_data);
                }catch (\Exception $e){
                    DB::rollBack();
                    return response()->json(encodeMsg(["message" => "请先确认图片是否已经添加或者图片id是否重复".$e->getMessage()],404), 404);
                }
            }
            DB::commit();
            return response()->json(encodeMsg($governmentDevice,201));
        } catch (QueryException $e) {
            DB::rollBack();
            // dd($e);
            return response()->json(encodeMsg(['message' => '市政部件添加失败!'],400));
        }
    }

    /**
     * 查看市政部件
     *
     * @bodyParam id int required 表ID
     *
     * @queryParam name string 设备名称
     * @queryParam mark string 编号
     * @queryParam address string 地址
     * @queryParam type_id int required 设备类型id 外键 设备类型表
     * @queryParam governmentCategory->name string 设备类型名称
     * @queryParam location point 经纬度-点 115.24556 25.14551
     * @queryParam areas polygon 护栏-面 (0 0,4 0,4 4,0 4,0 0)
     * @queryParam specs string 规格
     * @queryParam number integer 数量
     * @queryParam unit char 单位
     * @queryParam factory string 厂家
     * @queryParam contacts string 联系人
     * @queryParam mobile string 手机号码
     * @queryParam property_company string 产权单位
     * @queryParam principal_id int 负责人id 外键 员工表
     * @queryParam employees->name string 负责人
     * @queryParam phone string 电话
     * @queryParam rfid intger RFID绑定
     * @queryParam files->file->local_url string 附件url地址
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = GovernmentDevice::with('files')->find($id);
        if($data == []) {
            return response()->json(encodeMsg(["message" => "没有该市政部件信息!"], 404));
        } else {
            return response()->json(encodeMsg($data,200));
        }
    }

    /**
     * 修改市政部件
     *
     * @bodyParam id int required 表ID
     * @bodyParam name string 设备名称
     * @bodyParam mark string 编号
     * @bodyParam address string 地址
     * @bodyParam type_id int required 设备类型id 外键 设备类型表
     * @bodyParam location point 经纬度-点 115.24556 25.14551
     * @bodyParam areas polygon 护栏-面 (0 0,4 0,4 4,0 4,0 0)
     * @bodyParam specs string 规格
     * @bodyParam number integer 数量
     * @bodyParam unit char 单位
     * @bodyParam factory string 厂家
     * @bodyParam contacts string 联系人
     * @bodyParam mobile string 手机号码
     * @bodyParam property_company string 产权单位
     * @bodyParam principal_id int 负责人id 外键 员工表
     * @bodyParam phone string 电话
     * @bodyParam rfid intger RFID绑定
     * @bodyParam government_ids string 市政部件附件ids:1,2,3
     *
     * @queryParam name string 设备名称
     * @queryParam mark string 编号
     * @queryParam address string 地址
     * @queryParam type_id int required 设备类型id 外键 设备类型表
     * @queryParam location point 经纬度-点 115.24556 25.14551
     * @queryParam areas polygon 护栏-面 (0 0,4 0,4 4,0 4,0 0)
     * @queryParam specs string 规格
     * @queryParam number integer 数量
     * @queryParam unit char 单位
     * @queryParam factory string 厂家
     * @queryParam contacts string 联系人
     * @queryParam mobile string 手机号码
     * @queryParam property_company string 产权单位
     * @queryParam principal_id int 负责人id 外键 员工表
     * @queryParam phone string 电话
     * @queryParam rfid intger RFID绑定
     * @queryParam government_ids string 市政部件附件ids:1,2,3
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $governmentDevice = GovernmentDevice::find($id);
        if($governmentDevice == []) {
            return response()->json(encodeMsg(["message" => "没有该市政部件信息!"], 404));
        }
        DB::beginTransaction();
        try {
            $data = $request->all();
            // $data['location'] = \DB::raw("GeomFromText('Point({$request->input('location')})')");
            $location = $request->input('location','');
            if(!empty($location)){
                $data['location'] = Point::fromString($location);
            }
            $areas = $request->input('areas','');
            if(!empty($areas)){
                $data['areas'] = Polygon::fromString($areas);
            }
            if($request->has('government_ids')){
                $origin_files = GovenmentDeviceFile::where('government_id',$id)->get()->toArray();//图片原来的id号是好多 取出
                $origin_file_ids = array();//这个数组用于报错以前的所有file的id号
                if($origin_files != []){
                    foreach ($origin_files as $v){
                        array_push($origin_file_ids,$v['id']);
                    }
                }
                $file_data = [];
                $fileArr = explode(',',$request->get('government_ids'));
                foreach ($fileArr as $k=>$value){
                    $tmp = [];
                    $tmp['file_id'] = $value;
                    $tmp['government_id'] = $id;
                    array_push($file_data,$tmp);
                }
                try{
                    GovenmentDeviceFile::whereIn('id',$origin_file_ids)->delete();
                    GovenmentDeviceFile::insert($file_data);
                }catch (\Exception $e){
                    DB::rollBack();
                    return response()->json(encodeMsg(["message" => "请先确认图片是否已经添加或者图片id是否重复".$e->getMessage()],404), 404);
                }
            }
            $governmentDevice->update($data);
            DB::commit();
            return response()->json(encodeMsg($governmentDevice,200));
        } catch (QueryException $e) {
            DB::rollBack();
            return response()->json(encodeMsg(['message' => '市政部件修改失败!'],400));
        }
    }

    /**
     * 删除市政部件
     *
     *
     * @bodyParam id int required 市政部件ID
     * @response 204 {
     *   "message": "市政部件删除成功"
     * }
     *
     *
     * @response 404 {
     *  "message": "没有该市政部件信息"
     * }
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $governmentDevice = GovernmentDevice::find($id);
        if($governmentDevice == []) {
            return response()->json(encodeMsg(["message" => "没有该市政部件信息!"], 404));
        }
        if($governmentDevice->delete()) {
            return response()->json(encodeMsg(["message" => "市政部件删除成功!"], 204));
        } else {
            return response()->json(encodeMsg(["message" => "市政部件删除失败"], 400));
        }
    }

    /**
     * 批量删除市政部件
     *
     * @bodyParam ids int required id集合字符串[格式：ids=1,2,3]
     * @response 204 {
     *   "message": "市政部件删除成功"
     * }
     *
     *
     */
    public function delete($ids)
    {
        $listId = explode(',', $ids);
        GovernmentDevice::whereIn('id',$listId)->delete();
        return response()->json(encodeMsg(["message" => "市政部件删除成功!"], 204));
    }

    /**
     * 市政部件导入 excel
     *
     * @queryParam name string 设备名称
     * @queryParam mark string 编号
     * @queryParam address string 地址
     * @queryParam type_id int required 设备类型id 外键 设备类型表
     * @queryParam location point 经纬度-点 115.24556 25.14551
     * @queryParam areas polygon 护栏-面 (0 0,4 0,4 4,0 4,0 0)
     * @queryParam specs string 规格
     * @queryParam number integer 数量
     * @queryParam unit char 单位
     * @queryParam factory string 厂家
     * @queryParam contacts string 联系人
     * @queryParam mobile string 手机号码
     * @queryParam property_company string 产权单位
     * @queryParam principal_id int 负责人id 外键 员工表
     * @queryParam phone string 电话
     * @queryParam rfid intger RFID绑定
     *
     * @return \Illuminate\Http\Response
     */
    public function import(Request $request)
    {
        $data = excelImport($request);
        $governmentDevice = [];
        if(!empty($data)){
            foreach ($data as $k => $v) {
                unset($v[0]);
                foreach ($v as $key => $row) {
                    DB::beginTransaction();
                    try {
                        $governmentDevice[$k][$key]['name'] = $row[0];
                        $governmentDevice[$k][$key]['device_name'] = $row[1];
                        $governmentDevice[$k][$key]['device_tag'] = $row[2];
                        $governmentDevice[$k][$key]['address'] = $row[3];
                        if (!empty($row[4])) {
                            $governmentDevice[$k][$key]['location'] = Point::fromString($row[4]);
                        }
                        if (!empty($row[5])) {
                            $governmentDevice[$k][$key]['areas'] = Polygon::fromString($row[5]);
                        }
                        $governmentDevice[$k][$key]['service_time'] = $row[6];
                        $governmentDevice[$k][$key]['last_time'] = $row[7];
                        $governmentDevice[$k][$key]['next_time'] = $row[8];
                        $department_id = Department::where('name',$row[9])->first('id');
                        if (!empty($department_id)) {
                            $governmentDevice[$k][$key]['department_id'] = $department_id->id;
                        } else if(!empty($row[9])) {
                            $department['name'] = $row[9];
                            $info = Department::addData($department);
                            $governmentDevice[$k][$key]['department_id'] = $info->id;
                        }
                        $principal_id = Employee::where('name',$row[10])->first('id');
                        if (!empty($principal_id)) {
                            $governmentDevice[$k][$key]['principal_id'] = $principal_id->id;
                        } else if(!empty($row[10])) {
                            $employee['name'] = $row[10];
                            $info = Employee::addData($employee);
                            $governmentDevice[$k][$key]['principal_id'] = $info->id;
                        }
                        $governmentDevice[$k][$key]['phone'] = $row[11];
                        $data = $governmentDevice[$k][$key];
                        $res = GovernmentDevice::where(function($query) use ($data){
                            if(!empty($data['location'])){
                                $query->distance('location',$data['location'],10);
                            }
                            if(!empty($data['areas'])){
                                $query->distance('areas',$data['areas'],10);
                            }
                            unset($data['location']);
                            unset($data['areas']);
                            $query->where($data);
                        })->first();
                        if (empty($res)) {
                            GovernmentDevice::create($governmentDevice[$k][$key]);
                        }
                        DB::commit();
                    } catch (QueryException $e) {
                        DB::rollBack();
                        // dd($e);
                        return response()->json(encodeMsg(['message' => '导入失败!'],400));
                    }
                }
                unset($governmentDevice[$k][$key]);
            }
            unset($governmentDevice[$k]);
        }
        if(Storage::disk('public')->exists('uploads/'.$request->file('file')->getClientOriginalName())) {
            return response()->json(encodeMsg(['message' => '文件已上传!'],200));
        }
    }
}
